/**
 * 
 */
package com.jolestar.yayaweibotong.task;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jolestar.yayaweibotong.controller.AbstractAction;
import com.jolestar.yayaweibotong.util.RequestUtils;

/**
 * @author jolestar@gmail.com
 * 
 */
public class TaskAction extends AbstractAction {

	private Task task;

	/**
	 * 
	 */
	public TaskAction(Task task) {
		super(task.getName());
		this.task = task;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.controller.AbstractAction#doAction(javax.servlet
	 * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected String doAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = new HashMap<String, String>();
		Enumeration<String> requestNames = request.getParameterNames();
		while (requestNames.hasMoreElements()) {
			String name = requestNames.nextElement();
			String value = request.getParameter(name);
			params.put(name, value);
		}
		Map<String, String> headers = new HashMap<String, String>();
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String name = headerNames.nextElement();
			String value = request.getHeader(name);
			headers.put(name, value);
		}
		int retryLatterCount = RequestUtils.getIntHeader(request,
				Task.YAYA_TASK_RETRY_LATTER_COUNT_HEADER, 0);
		if (retryLatterCount > 0) {
			log.info(Task.YAYA_TASK_RETRY_LATTER_COUNT_HEADER + ":"
					+ retryLatterCount);
		}
		int retryCount = RequestUtils.getIntHeader(request,
				"X-AppEngine-TaskRetryCount", 0);
		String uri = request.getRequestURI();
		boolean result = this.task.run(uri, headers, params);
		if (result) {
			return null;
		}
		if (!result && retryCount <= 5) {
			response.sendError(500);
		} else {
			log.severe("task (url:" + uri + ") retry count > 5");
		}
		return null;
	}

	@Override
	public String getPath() {
		return "/_ah/queue/" + this.getName();
	}

}
